<template>
  <div class="work_area">
    <div class="canvas_size">
      <el-space :size="10" spacer="✖">
        <el-input-number
          v-model="canvasStore.canvasWidth"
          :precision="0"
          :step="1"
        />
        <el-input-number
          v-model="canvasStore.canvasHeight"
          :precision="0"
          :step="1"
        />
      </el-space>
    </div>
    <canvas
      ref="myCanvas"
      id="myCanvas"
      @contextmenu.prevent="contextmenu"
      :width="canvasStore.canvasWidth"
      :height="canvasStore.canvasHeight"
    >
    </canvas>
    <context-menu
      v-if="myCanvas"
      ref="mouseMenuEl"
      :el="myCanvas"
      :menuList="menuList"
    >
    </context-menu>
  </div>
</template>
<script setup lang="ts">
import { onMounted, Ref, ref, watch } from 'vue'
import { useCanvasStore } from '@/store/modules/canvasStore'
import ContextMenu from '@/components/ContextMenu.vue'
const canvasStore = useCanvasStore()
const myCanvas = ref()
const _throttleRunning = ref(false)
// 当前操作的canvas数据
watch(
  () => canvasStore.canvasPage,
  (val, oldVal) => {
    console.log(val, oldVal, 'val, oldVal')
    throttle(painting, 50)
  },

  { deep: true }
)
onMounted(() => {
  if (myCanvas.value) {
    canvasStore.ctx = myCanvas.value.getContext('2d')
    canvasStore.canvas = myCanvas.value
  }
  painting()
})
/**
 * 节流
 * @param {Function} 执行函数
 * @param {Number} delay 延时ms
 */
function throttle(fn: () => void, delay = 500) {
  if (_throttleRunning.value) {
    return
  }
  _throttleRunning.value = true
  fn()
  setTimeout(() => {
    _throttleRunning.value = false
  }, delay)
}
function pageSet() {}
const menuList = ref([
  {
    label: '页面配置',
    fn: pageSet,
  },
])
const mouseMenuEl = ref()
const contextmenu = (e: any) => {
  e.preventDefault()
  const { x, y } = e
  mouseMenuEl.value.show(x, y)
}

async function painting() {
  canvasStore.renderAll()
}
</script>
<style lang="scss" scoped>
.work_area {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .canvas_size {
    display: flex;
  }
  #myCanvas {
    margin-top: 20px;
    border: 1px #ccc solid;
  }
}
</style>
